package com.appspot.zarm.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.zarm.game.BoardStorage;
import com.appspot.zarm.game.Player;
import com.appspot.zarm.game.PlayerType;
import com.appspot.zarm.game.Rival;

public class Dispatcher extends HttpServlet {

	private static final long serialVersionUID = 7581075472706864451L;

	/**
	 * Action values
	 */
	public static final String ACTION_PARAM = "action";
	public static final String DATA_PARAM = "data";

	/**
	 * Constants
	 */
	private static final String BOARD_STORAGE_ATTR_NAME = "BoardStorage";
	private static final String PLAYER_ATTR_NAME = "Player";
	private static final String RIVAL_ATTR_NAME = "Rival";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String action = (String) request.getParameter(ACTION_PARAM);
		String data = (String) request.getParameter(DATA_PARAM);

		if (action != null) {
			GameAction gameAction = new GameActionFactory().getGameAction(GameActionFactory.GOMOKU);
			BoardStorage boardStorage = getBoardStorage();
			Player player = getPlayer();
			Rival rival = getRival();
			String result = gameAction.process(boardStorage, player, rival, action, data);
			if (result != null){
				print(response, result);
			}
		} else {
			goHomePage(request, response);
		}
	}

	private BoardStorage getBoardStorage() {
		BoardStorage bs = (BoardStorage) getServletContext().getAttribute(BOARD_STORAGE_ATTR_NAME);
		if (bs == null) {
			bs = new BoardStorage();
			getServletContext().setAttribute(BOARD_STORAGE_ATTR_NAME, bs);
		}
		return bs;
	}

	private Player getPlayer(){
		Player player = (Player) getServletContext().getAttribute(PLAYER_ATTR_NAME);
		if (player == null){
			player = new Player("1", PlayerType.ONE);
		} 
		return player;
	}
	
	private Rival getRival(){
		Rival rival = (Rival) getServletContext().getAttribute(RIVAL_ATTR_NAME);
		if (rival == null){
			rival = new Rival("2", PlayerType.TWO);
		} 
		return rival;

	}
	
	private void goHomePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		getServletConfig().getServletContext().getRequestDispatcher("/layout.jsp").forward(request, response);
	}

    private void print(HttpServletResponse response, String value) throws IOException {
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		pw.print(value);
	}

}
